package com.hfjyz.exam.dao;

import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.hfjyz.exam.command.PaperListCommand;
import com.hfjyz.exam.model.Paper;
import com.hfjyz.exam.model.PaperDetail;
import com.hfjyz.exam.model.PaperSection;
import com.hfjyz.exam.model.Question;
import com.hfjyz.exam.model.QuestionOptions;

public class PaperDaoImpl extends BaseDaoImpl<Paper, Integer> implements
		PaperDao {

	protected PaperDaoImpl() {
		super(Paper.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Paper> find(final PaperListCommand cmd) throws Exception {
		DetachedCriteria dc = DetachedCriteria.forClass(Paper.class);
		Calendar cl = Calendar.getInstance();
		// cl.set(Calendar.MINUTE, 0);
		cl.set(Calendar.SECOND, 0);
		cl.set(Calendar.MILLISECOND, 0);
		Date now = cl.getTime();
		dc.add(Restrictions.le("starttime", now)).add(
				Restrictions.ge("endtime", now));
		List<Paper> papers = hibernateTemplate.findByCriteria(dc);
		return papers;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Paper getForExam(final Integer pid) throws Exception {
		Paper p = (Paper) hibernateTemplate.get(Paper.class, pid);
		if (p == null) {
			return null;
		}
		DetachedCriteria dc = DetachedCriteria.forClass(PaperSection.class)
				.add(Restrictions.eq("paper.id", pid));
		List<PaperSection> pss = hibernateTemplate.findByCriteria(dc);
		p.setPaperSections(pss);

		for (PaperSection ps : pss) {
			dc = DetachedCriteria.forClass(PaperDetail.class)
					.add(Restrictions.eq("paper.id", pid))
					.add(Restrictions.eq("paperSection.id", ps.getId()))
					.addOrder(Order.asc("seq"));
			ps.setPaperDetails(hibernateTemplate.findByCriteria(dc));
			Collections.shuffle(ps.getPaperDetails());
			for (PaperDetail pd : ps.getPaperDetails()) {
				Question question = pd.getQuestion();
				dc = DetachedCriteria.forClass(QuestionOptions.class)
						.add(Restrictions.eq("question.id", question.getId()))
						.add(Restrictions.isNotNull("qoption"));
				question.setQuestionOptionses(hibernateTemplate
						.findByCriteria(dc));
			}
		}
		return p;
	}
}
